﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using RDotNet;
using RDotNet.Internals;
using RDotNet.NativeLibrary;
using RDotNet.Utilities;
using RDotNet.Diagnostics;
using RDotNet.Dynamic;


namespace Data_ConverteR
{
    public partial class Form1 : Form
    {
        public string fName;
        public string file;
        public string folder;
        public REngine engine;
        public Form1()
        {
            InitializeComponent();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            DialogResult result = inOPD.ShowDialog();
            if (result == DialogResult.OK) // Test result.
            {
                file = inOPD.FileName;
                try
                {
                    txtIn.Text = file;
                    fName = file.Replace(@"\", "/");
                    btnDo.Enabled = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        private void btnChoose_Click(object sender, EventArgs e)
        {
            DialogResult result = outFBD.ShowDialog();
            if (result == DialogResult.OK)
            {
                folder = outFBD.SelectedPath;
                folder = folder.Replace(@"\", "/");
                txtOut.Text = folder;
            }
        }

        private void btnDo_Click(object sender, EventArgs e)
        {
            //read file into R
            int inType = cbIn.SelectedIndex;
            int outType = cbOut.SelectedIndex;
            Object selectedItem = cbOut.SelectedItem;
            DataFrame rdata = Utils.ConvertData(engine, fName, inType);
            lblCases.Text = rdata.RowCount.ToString() + @" Cases and";
            lblVar.Text = rdata.ColumnCount.ToString() + @" Variables";
            if (folder == null)
            {
                folder = Path.GetDirectoryName(file);
            }
            string fileName = Path.GetFileNameWithoutExtension(fName);
            //write to target file
                if (rdata != null) { 
                try {
                    Utils.WriteData(engine, rdata, outType,  folder.Replace(@"\", "/"), fileName);
                }
                catch (Exception ex) {
                    MessageBox.Show(ex.Message);
                }
            }
            txtIn.Text = "";
            txtOut.Text = "";
            fName = "";
            btnDo.Enabled = false;
            btnOpen.Focus();
            string success = @"{0} Cases and {1} Variables Transferred Successfully" + Environment.NewLine + "Do you want to open folder to view transferred files?";
            success = String.Format(success, new object[]{rdata.RowCount , rdata.ColumnCount});
            DialogResult dr3 = MessageBox.Show(success,"Successful", MessageBoxButtons.OKCancel);   
            if(dr3 == DialogResult.OK){
                Process.Start(folder);
            }
            else
            {

            }
            
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //set environment variables
            try
            {
                REngine.SetEnvironmentVariables();
            }
            catch (Exception ex)
            {
                string alert = ex.Message + Environment.NewLine + @"Please read installation guide!";
                MessageBox.Show(alert);
       
            }
            // try to get engine instance
            try
            {
                this.engine = REngine.GetInstance();
            }
            catch (Exception ex)
            {
                string alert1 = ex.Message + Environment.NewLine + @"Do you want to open Setting Tab";
                MessageBox.Show(alert1);
            }
            // try to load R packages
            try
            {
                engine.Evaluate("library('foreign')");
                engine.Evaluate("library('memisc')");
                engine.Evaluate("library('Hmisc')");
            }
            catch (Exception ex)
            {
                string alert2 = ex.Message + Environment.NewLine + @"Do you want to open Setting Tab";
                MessageBox.Show(alert2);
            }
            //check .net version
        
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (engine != null)
            {
                engine.Dispose();
            }
        }

        private void cbIn_SelectedIndexChanged(object sender, EventArgs e)
        {
            int inSelect = cbIn.SelectedIndex;
            switch (inSelect) { 
                case 0:
                    inOPD.Filter = "CSV (*.csv) | *.csv";
                    break;
                case 1:
                    inOPD.Filter = "Stata (*.dta)|*.dta";
                    break;
                case 2:
                    inOPD.Filter = "SPSS (*.sav)|*.sav";                   
                    break;
                case 3:
                    inOPD.Filter = "SAS Transport Format (*.xpt)|*.xpt";
                    break;
                case 4:
                    inOPD.Filter = "Systat (*.dta) | *.dta";
                    break;
            }
        }
   
    }
}
